const { BaseController } = require('../Base')

let fileAllList = []

class Api extends BaseController {
  // 获取模拟数据文件
  mockdata(ctx) {
    try {
      const dataPath = this.getSrcPath('public/mock/')
      let result = require(`${dataPath}/${ctx.query.name}.json`)
      ctx.body = result
    } catch (error) {
      console.log(error, '-->>> mockdata error')
      ctx.body = this.resError('文件读取失败!')
    }
  }
  // mockjs测试列表
  listData(ctx) {
    const res = this.servers.MockData.listData(ctx)
    ctx.body = this.resSuccess(res)
  }
  // mockjs测试列表 - 延迟
  async listDataSleep(ctx) {
    const time = ctx.query.time || 500
    await this.tools.sleep(time)
    const res = this.servers.MockData.listData(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 接口缓存
  async apiCache(ctx) {
    const apiCachePath = this.getSrcPath('public/mock/apiCache')
    await this.tools.file.checkDir(apiCachePath)
    let { url, value } = ctx.request.body
    let urlParse = url.replace(/\//g, '_')
    this.tools.file.writeTxt(
      `${apiCachePath}/${urlParse}.json`,
      JSON.stringify({ data: value }, null, '\t')
    )
    ctx.body = this.resSuccess({ url, value })
  }
  // 获取接口缓存
  getApiCache(ctx) {
    try {
      const dataPath = this.getSrcPath('public/mock/apiCache')
      let name = ctx.query.name.replace(/\//g, '_')
      let result = require(`${dataPath}/${name}.json`)
      ctx.body = this.resSuccess(result.data)
    } catch (error) {
      console.log(error, '-->>> mockdata error')
      ctx.body = this.resError('缓存读取失败!')
    }
  }
  // 评论列表
  commentList(ctx) {
    const res = this.servers.MockData.commentList(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 角色列表 分页
  userList(ctx) {
    const res = this.servers.MockData.userList(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 新闻列表
  async newsList(ctx) {
    const res = await this.servers.HomeServer.newsList(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 东方网新闻列表
  async newsListDf(ctx) {
    const res = await this.servers.HomeServer.newsListDf(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 富文本
  richtext(ctx) {
    const res = this.servers.PublicData.richtext(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 城市列表
  cityList(ctx) {
    const res = this.servers.PublicData.getArea(ctx)
    ctx.body = this.resSuccess(res)
  }
  // 所有城市列表[树状]
  cityListAll(ctx) {
    const res = this.servers.PublicData.getAreaAll(ctx)
    ctx.body = this.resSuccess(res)
  }
}

const ex = new Api()
module.exports = ex
